package com.aisino.api.util;

import com.aisino.api.model.FileInfo;

import java.util.Base64;

public class FileUtil {

    public static FileInfo getFileInfo(String base64Data) {
        // 如果Base64字符串包含data URI前缀，则从中提取类型
        if (base64Data.startsWith("data:")) {
            String[] parts = base64Data.split(",");
            if (parts.length > 0) {
                String mimeType = parts[0].substring(5); // 移除"data:"前缀
                if (mimeType.contains(";")) {
                    mimeType = mimeType.substring(0, mimeType.indexOf(";"));
                }
                // 从 MIME 类型提取后缀
                String extension = getFileExtensionFromMimeType(mimeType);
                return new FileInfo(extension, mimeType);
            }
        }

        // 否则通过文件签名检测
        try {
            String[] parts = base64Data.split(",");
            String base64Part = parts[parts.length - 1];
            byte[] decodedBytes = Base64.getDecoder().decode(base64Part);

            if (isJPEG(decodedBytes)) {
                return new FileInfo("jpg", "image/jpeg");
            } else if (isPNG(decodedBytes)) {
                return new FileInfo("png", "image/png");
            } else if (isGIF(decodedBytes)) {
                return new FileInfo("gif", "image/gif");
            } else if (isBMP(decodedBytes)) {
                return new FileInfo("bmp", "image/bmp");
            }
        } catch (Exception e) {
        }

        return new FileInfo("jpg", "image/jpeg"); // 默认类型
    }

    // 保留原有的方法以保持向后兼容
    public static String detectFileType(String base64Data) {
        return getFileInfo(base64Data).getExtension();
    }

    // 根据 MIME 类型获取文件后缀
    private static String getFileExtensionFromMimeType(String mimeType) {
        switch (mimeType) {
            case "image/jpeg":
                return "jpg";
            case "image/png":
                return "png";
            case "image/gif":
                return "gif";
            case "image/bmp":
                return "bmp";
            default:
                return "jpg"; // 默认
        }
    }

    private static boolean isJPEG(byte[] data) {
        return data.length > 2 && data[0] == (byte) 0xFF && data[1] == (byte) 0xD8;
    }

    private static boolean isPNG(byte[] data) {
        return data.length > 3 && data[0] == (byte) 0x89 && data[1] == (byte) 0x50
                && data[2] == (byte) 0x4E && data[3] == (byte) 0x47;
    }

    private static boolean isGIF(byte[] data) {
        return data.length > 2 && data[0] == (byte) 0x47 && data[1] == (byte) 0x49
                && data[2] == (byte) 0x46;
    }

    private static boolean isBMP(byte[] data) {
        return data.length > 1 && data[0] == (byte) 0x42 && data[1] == (byte) 0x4D;
    }
}
